# coding:utf-8
import os

import facade
import math
import pymysql as mysql
import requests
from xjlibrary.our_file_dir import BaseDir, ImageFile

curpath = BaseDir.get_file_dir_absolute(__file__)
TopPath = BaseDir.get_upper_dir(curpath, -2)
dirPath = BaseDir.get_new_path(TopPath, "download", "bh_botu", "download", "cover")
BaseDir.create_dir(dirPath)
configfile = BaseDir.get_new_path(curpath, "db.ini")

er_photo = BaseDir.get_new_path(curpath, "err", "er.jpg")
er_photo2 = BaseDir.get_new_path(curpath, "err", "er2.jpg")


class DownCover(object):

    def __init__(self):
        self.logger = facade.get_streamlogger()
        self.mysqlutils = facade.MysqlUtiles(configfile, "db", logger=self.logger)
        self.proxies = {
            "http": "192.168.30.176:8034",
            "https": "192.168.30.176:8034",
        }
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.108 Safari/537.36',
        }
        self.read_err1()
        self.read_err2()

    def read_err1(self):
        with open(er_photo, "rb") as f:
            self.er_data = f.read()

    def read_err2(self):
        with open(er_photo2, "rb") as f:
            self.er_data2 = f.read()

    def select(self):
        sql = "select rawid,coverurl from article where coverstat=0 and coverfailcount <= 3 and coverurl is not NULL limit 10000"
        rows = self.mysqlutils.SelectFromDB(sql)
        if rows:
            for row in rows:
                if not self.down_cover(row):
                    # 如果返回false 代表需要重新select
                    break
            return True
        else:
            return False

    def down_cover(self, row):
        rawid = row[0]
        url = row[1]
        pathroot = os.path.join(dirPath, str(math.ceil(int(rawid) / 1000)))
        file_path = os.path.join(pathroot, str(rawid) + '.jpg')
        if os.path.exists(file_path):
            print("图片存在")
            return True
        url_phono = "http://10.5.23.17:8081/" + url
        BoolResult, errString, r = facade.BaseRequest(url_phono,
                                                      endstring="",
                                                      proxies=self.proxies,
                                                      headers=self.headers,
                                                      timeout=30)
        if BoolResult:
            if self.er_data == r.content:
                self.logger.info(str(rawid) + ": 图片错误")
                sql = "update article set coverstat = -1 where coverurl = '%s' " % (url)
                self.mysqlutils.ExeSqlToDB(sql)
                return False
            if self.er_data2 == r.content:
                self.logger.info(str(rawid) + ": 图片错误2")
                sql = "update article set coverstat = -2 where coverurl = '%s' " % (url)
                self.mysqlutils.ExeSqlToDB(sql)
                return False
            if not os.path.exists(pathroot):
                os.makedirs(pathroot)
            if ImageFile.img_to_format_jpg(r.content, file_path):
                self.logger.info("图片保存成功")
                sql = "update article set coverstat = 1 where rawid = '%s' " % (rawid)
                self.mysqlutils.ExeSqlToDB(sql)
                return True
            else:
                # 半截图片
                sql = "update article set coverstat = -3 where coverurl = '%s' " % (url)
                self.mysqlutils.ExeSqlToDB(sql)
                return True

        else:
            sql = "update article set coverfailcount = coverfailcount+1 where rawid = '%s' " % (rawid)
            self.mysqlutils.ExeSqlToDB(sql)
            return True


if __name__ == "__main__":
    down = DownCover()
    while True:
        if not down.select():
            break
